// 用户业务逻辑服务
import {
  wechatOneTapLogin as apiWechatLogin,
  getUserInfo as apiGetUserInfo,
  getFollowList as apiGetFollowList,
  getFansList as apiGetFansList,
  followUser as apiFollowUser,
  unfollowUser as apiUnfollowUser,
} from '@/api';
import { loginWeChatMP } from '../utils/wechat';
import { post } from '@/utils/request';
import { useUserStore, useAppStore } from '@/stores';
import type { UserInfo, FollowListParams } from '@/types/user';
import type { ApiResponse } from '@/types/common';

/**
 * 用户服务类
 */
export class UserService {
  /**
   * 微信一键登录
   */
  static async wechatLogin(phoneCode: string) {
    const userStore = useUserStore();
    const appStore = useAppStore();

    try {
      userStore.setLoading(true);

      // 获取微信登录码
      const loginResult = (await loginWeChatMP()) as any;
      const loginCode = loginResult.code;

      if (!loginCode) {
        throw new Error('获取微信登录码失败');
      }

      // 调用登录接口
      const response = await apiWechatLogin({
        loginCode,
        phoneCode,
      } as { loginCode: string; phoneCode: string });

      if (response.code === 200) {
        // 保存登录信息到 Store 和本地存储
        const { token, userInfo, expiresAt } = response.data;
        await this.saveLoginInfo(token, userInfo, expiresAt);
        userStore.setUserInfo(userInfo);
        appStore.showToast('登录成功', 'success');
        return response.data;
      } else {
        throw new Error(response.msg || '登录失败');
      }
    } catch (error: any) {
      console.error('登录失败:', error);
      appStore.showToast(error.message || '登录失败', 'error');
      throw error;
    } finally {
      userStore.setLoading(false);
    }
  }

  /**
   * 获取用户信息
   */
  static async getUserInfo(): Promise<UserInfo> {
    const userStore = useUserStore();
    const appStore = useAppStore();

    try {
      userStore.setLoading(true);
      const response = await apiGetUserInfo();

      if (response.code === 200) {
        userStore.setUserInfo(response.data);
        return response.data;
      } else {
        throw new Error(response.msg || '获取用户信息失败');
      }
    } catch (error: any) {
      console.error('获取用户信息失败:', error);
      appStore.showToast(error.message || '获取用户信息失败', 'error');
      throw error;
    } finally {
      userStore.setLoading(false);
    }
  }

  /**
   * 获取关注列表
   */
  static async getFollowList(params: FollowListParams) {
    try {
      const response = await apiGetFollowList(params);
      if (response.code === 200) {
        return response.data;
      } else {
        throw new Error(response.msg || '获取关注列表失败');
      }
    } catch (error) {
      console.error('获取关注列表失败:', error);
      throw error;
    }
  }

  /**
   * 获取粉丝列表
   */
  static async getFansList(params: FollowListParams) {
    try {
      const response = await apiGetFansList(params);
      if (response.code === 200) {
        return response.data;
      } else {
        throw new Error(response.msg || '获取粉丝列表失败');
      }
    } catch (error) {
      console.error('获取粉丝列表失败:', error);
      throw error;
    }
  }

  /**
   * 关注用户
   */
  static async followUser(userId: string) {
    const appStore = useAppStore();

    try {
      const response = await apiFollowUser(userId);
      if (response.code === 200) {
        appStore.showToast('关注成功', 'success');
        return true;
      } else {
        throw new Error(response.msg || '关注失败');
      }
    } catch (error: any) {
      console.error('关注用户失败:', error);
      appStore.showToast(error.message || '关注失败', 'error');
      throw error;
    }
  }

  /**
   * 取消关注用户
   */
  static async unfollowUser(userId: string) {
    const appStore = useAppStore();

    try {
      const response = await apiUnfollowUser(userId);
      if (response.code === 200) {
        appStore.showToast('取消关注成功', 'success');
        return true;
      } else {
        throw new Error(response.msg || '取消关注失败');
      }
    } catch (error: any) {
      console.error('取消关注用户失败:', error);
      appStore.showToast(error.message || '取消关注失败', 'error');
      throw error;
    }
  }

  /**
   * 保存登录信息到本地存储
   */
  private static async saveLoginInfo(token: string, userInfo: UserInfo, expiresAt: number) {
    try {
      uni.setStorageSync('token', token);
      uni.setStorageSync('userInfo', userInfo);
      uni.setStorageSync('userId', userInfo.uuid);
      uni.setStorageSync('expiresAt', expiresAt);
    } catch (error) {
      console.error('保存登录信息失败:', error);
    }
  }

  /**
   * 登出用户
   */
  static async logout() {
    const userStore = useUserStore();
    const appStore = useAppStore();

    try {
      // 调用登出接口
      const response = await post<ApiResponse>('/c/user/logout');

      if (response.code === 200) {
        appStore.showToast('登出成功', 'success');
      }
    } catch (error) {
      console.error('登出失败:', error);
      // 即使接口失败，也要清除本地信息
    } finally {
      // 清除用户信息和跳转登录页
      userStore.logout();
    }
  }

  /**
   * 清除登录信息
   */
  static clearLoginInfo() {
    const userStore = useUserStore();
    userStore.clearUserInfo();
  }

  /**
   * 检查登录状态
   */
  static isLoggedIn(): boolean {
    try {
      const token = uni.getStorageSync('token');
      const expiresAt = uni.getStorageSync('expiresAt');

      if (!token || !expiresAt) {
        return false;
      }

      // 检查token是否过期
      return Date.now() < expiresAt;
    } catch (error) {
      console.error('检查登录状态失败:', error);
      return false;
    }
  }
}
